import os

from common import constants


class Util:

    @staticmethod
    def find_files_with_suffix(folder_path, suffix):
        """
        扫描文件夹下所有包含指定后缀的文件
        :param folder_path: 文件夹
        :param suffix: 文件后缀
        :return: 符合条件的文件完整路径列表
        """
        matching_files = []
        for root, dirs, files in os.walk(folder_path):
            for file in files:
                if file.endswith(suffix):
                    file_path = os.path.join(root, file).replace('\\', '/')
                    matching_files.append(file_path)
        return matching_files

    @staticmethod
    def find_project_root():
        """
        查找根目录
        :return: 根目录的绝对路径
        """
        current_dir = os.path.abspath(os.path.dirname(__file__))
        while True:
            if (
                    os.path.exists(os.path.join(current_dir, constants.MAIN_PROGRAM)) or
                    os.path.exists(os.path.join(current_dir, f"{constants.MAIN_PROGRAM}.py")) or
                    os.path.exists(os.path.join(current_dir, f"{constants.MAIN_PROGRAM}.exe"))
            ):
                return current_dir
            parent_dir = os.path.abspath(os.path.join(current_dir, os.pardir))
            if parent_dir == current_dir:
                break
            current_dir = parent_dir
        return None

    @staticmethod
    def get_file_path(dir_path, file_name):
        file_path = f"{dir_path}/{file_name}"
        # 路径标准化，统一目录符号
        return os.path.normpath(file_path)

    @staticmethod
    def unified_static_path(static_type):
        """
        获取静态文件统一的保存目录（相对于根目录）
        :param static_type: 静态文件的类型，截图、日志或者其它
        :return: 系统标准目录
        """
        root_directory = Util.find_project_root()
        if root_directory is None:
            root_directory = "./"
        project_path = f"{root_directory}/{static_type}"
        if not os.path.exists(project_path):
            os.makedirs(project_path)
        # 路径标准化，统一目录符号
        return os.path.normpath(project_path)

    @staticmethod
    def read_requirements():
        """
        读取当前项目的环境依赖
        :return: 依赖列表
        """
        root_dir = Util.find_project_root()
        with open(Util.get_file_path(root_dir, constants.ENVI_PROGRAM)) as f:
            requirements = f.read().splitlines()
        return [req.split('==')[0] for req in requirements]
